package com.jiajia.datasource;

import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zjiajia
 * @date 2024/7/9 14:56
 */

@Component
public class DynamicDataSource extends AbstractRoutingDataSource {

    public DynamicDataSource(LoadDataSource loadDataSource){
        Map<String, DataSource> allDataSource = loadDataSource.loadAllDataSource();
        super.setTargetDataSources(new HashMap<>(allDataSource));
        super.setDefaultTargetDataSource(allDataSource.get(DataSourceType.DEFAULT_DS_NAME));
        super.afterPropertiesSet();

    }

    @Override
    protected Object determineCurrentLookupKey() {
        return DynamicDatasourceContextHolder.getDataSourceType();
    }
}
